//
//  ZYFeedBackViewModel.m
//  YiLin
//
//  Created by Zyark on 2018/7/12.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYFeedBackViewModel.h"
#import "AFNetWorkUtils.h"

@interface ZYFeedBackViewModel()
@property(nonatomic,strong) RACCommand *commitCommand;
@end

@implementation ZYFeedBackViewModel
-(RACCommand *)commitCommand{
    if(!_commitCommand){
        @weakify(self);
        _commitCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_GET_SYSTEM_MESSAGE_URL];
            NSLog(@"%@",url);
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                //校验数据
                BOOL success = [self checkData:subscriber];
                if(!success){
                    return nil;
                }
                [self doCommit:subscriber];
                return nil;
            }];
        }];
    }
    return _commitCommand;
}

/**
 校验数据
 @param subscriber subscriber
 @return 是否成功
 */
-(BOOL)checkData:(id<RACSubscriber>)subscriber{
    if(NULLString(self.description)){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_DESCRIPTION_EMPTY]]];
        [subscriber sendCompleted];
        return NO;
    }
    if(NULLString(self.link)){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_LINK_EMPTY]]];
        [subscriber sendCompleted];
        return NO;
    }
    if(![ZYBasicHelper validateEmail:self.link] && ![ZYBasicHelper validateQQ:self.link]){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_LINK]]];
        [subscriber sendCompleted];
        return nil;
    }
    return YES;
}


-(void)doCommit:(id<RACSubscriber>)subscriber{
    NSDictionary *params;
    NSString *url = @"";
    params = @{@"description":self.desc,@"link":self.link,@"userId":[NSNumber numberWithInteger:[ZYConfig userId]],@"ssid":[ZYConfig loginToken]};
    url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_COMMIT_FEED_BACK];
    [[AFNetWorkUtils racPOSTWithURL:url params:params] subscribeNext:^(id x) {
        RACTuple *tuple = [RACTuple tupleWithObjects:[NSNumber numberWithBool:YES], nil];
        [subscriber sendNext:tuple];
        [subscriber sendCompleted];
    } error:^(NSError *error) {
        [subscriber sendError:error];
        [subscriber sendCompleted];
    }];
}

@end
